package com.example.dragandview.http;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.dragandview.R;
import com.example.dragandview.http.adaptar.WxarticleAdaptar;
import com.example.dragandview.http.model.Wxarticle;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.HttpsURLConnection;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class HttpActivity extends Activity {
    private Button btn_retrofit,btn_httpurl,btn_loadBigImage,btn_okhttp;
    private Gson gson = new Gson();
    public static final int WHAT_LOADER_RESULT = 1;
    private static Handler mHandler;
    private RecyclerView mResultList;
    private WxarticleAdaptar mResultAdapter;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.http_index);

        btn_retrofit = findViewById(R.id.btn_retrofit);
        btn_httpurl = findViewById(R.id.btn_httpurl);
        btn_okhttp = findViewById(R.id.btn_okhttp);
        btn_okhttp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(HttpActivity.this,OkHttpActivity.class));
            }
        });
        btn_loadBigImage = findViewById(R.id.btn_loadBigImage);
        btn_httpurl.setOnClickListener(v -> httpConn());
        btn_retrofit.setOnClickListener(v -> {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("https://wanandroid.com/")
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
            HttpService api = retrofit.create(HttpService.class);
            //异步
            api.getResponse().enqueue(new Callback<List<Wxarticle>>() {
                @Override
                public void onResponse(Call<List<Wxarticle>> call, Response<List<Wxarticle>> response) {
                    System.out.println("sucess");
                    System.out.println(response.code());
                    System.out.println(response.body().toString());
                    System.out.println(gson.toJson(response.body()));
                }

                @Override
                public void onFailure(Call<List<Wxarticle>> call, Throwable t) {
                    System.out.println("failed==============");
                    System.out.println(t.toString());
                }
            });
            //同步
//                api.getResponse().execute();
        });
        btn_loadBigImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadBigImage();
            }
        });
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch(msg.what) {
                    case WHAT_LOADER_RESULT:
                        Wxarticle result = (Wxarticle) msg.obj;
                        refreshResultList(result);
                        break;
                }
            }
        };
        mResultList = findViewById(R.id.result_list);
        mResultList.setLayoutManager(new LinearLayoutManager(this));
        mResultAdapter = new WxarticleAdaptar();
        mResultList.setAdapter(mResultAdapter);
    }
    private void refreshResultList(Wxarticle result) {
        mResultAdapter.setData(result);
    }
    private void httpConn(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL("https://wanandroid.com/wxarticle/chapters/json");
                    HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
                    httpsURLConnection.setRequestMethod("GET");
                    //设置请求超时时间
                    httpsURLConnection.setConnectTimeout(1000);
                    httpsURLConnection.setRequestProperty("accept", "*/*");
                    httpsURLConnection.setRequestProperty("connection", "keep-alive");
                    httpsURLConnection.setRequestProperty("Accept-Language", "zh-CN,zh");

                    //开始连接
                    httpsURLConnection.connect();

                    int responsecode = httpsURLConnection.getResponseCode();
                    if(responsecode == 200){
                        System.out.println("请求成功");
                        //获取返回内容
                        Map<String, List<String>> headerFields = httpsURLConnection.getHeaderFields();
                        Set<Map.Entry<String, List<String>>> entries = headerFields.entrySet();
                        for (Map.Entry<String, List<String>> entry : entries) {
                            System.out.println(entry.getKey() + " === " + entry.getValue());
                        }
                        InputStream inputStream = httpsURLConnection.getInputStream();
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                        String line;
                        String json = "";
                        while ((line = bufferedReader.readLine()) != null) {
                            json = line;
                            System.out.println(line);
                        }
                        bufferedReader.close();
                        Message message = mHandler.obtainMessage();
                        message.what = WHAT_LOADER_RESULT;
                        Gson gson = new Gson();
                        message.obj = gson.fromJson(json,Wxarticle.class);
                        mHandler.sendMessage(message);
                    }else {
                        System.out.println("请求失败");
                    }

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    public void requestImage(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                loadImage();
            }
        }).start();
    }
    private void loadImage() {
        try {
            URL url = new URL("https://i0.hdslb.com/bfs/sycp/creative_img/202004/55a442955265dc9760a505102efc7c4e.jpg");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setConnectTimeout(10000);
            httpURLConnection.connect();
            InputStream is = httpURLConnection.getInputStream();
            final Bitmap bitmap = BitmapFactory.decodeStream(is);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ImageView resultView = findViewById(R.id.image_result);
                    resultView.setImageBitmap(bitmap);
                }
            });
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    public void loadBigImage() {
        ImageView imageView = this.findViewById(R.id.image_container);
        BitmapFactory.Options options = new BitmapFactory.Options();
        //If set to true, the decoder will return null (no bitmap)
        //设置为true以后呢，不是真的载入到内存中，只是获取到图片的相关信息
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(getResources(),R.mipmap.mv1,options);
        int width = options.outWidth;
        int height = options.outHeight;
        int measuredWidth = imageView.getMeasuredWidth();
        int measuredHeight = imageView.getMeasuredHeight();
        int sampleSize;
        if(width < measuredWidth || height < measuredHeight) {
            sampleSize = 1;
        } else {
            int scaleX = width / measuredWidth;
            int scaleY = height / measuredHeight;
            sampleSize = scaleX > scaleY ? scaleX : scaleY;
        }
        options.inSampleSize = sampleSize;
        //If set to true, the decoder will return null (no bitmap)
        //要变成false了，因为真的要载入到内存中了
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.mv1,options);
        imageView.setImageBitmap(bitmap);
    }
}








